package cn.bellychang.leetcode.question125;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author ChangLiang
 * @date 2021/3/12
 */
public class Solution3 {

    public boolean isPalindrome(String s) {

        String str = convert2LowerCaseString(s);
        char[] chars = str.toCharArray();

        Deque<Character> stack = new ArrayDeque<>();
        int mid = chars.length >> 1;
        for (int i = 0; i < mid; i++) {
            stack.push(chars[i]);
        }
        if (chars.length % 2 == 0) {
            for (int i = mid; i < chars.length; i++) {

                if (stack.size() == 0) {
                    return false;
                }

                if (chars[i] != stack.pop()) {
                    return false;
                }
            }
        } else {
            for (int i = mid+1; i < chars.length; i++) {

                if (stack.size() == 0) {
                    return false;
                }

                if (chars[i] != stack.pop()) {
                    return false;
                }
            }
        }
        return true;
    }

    private String convert2LowerCaseString(String s) {
        StringBuilder result = new StringBuilder();
        s = s.toLowerCase();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {

            if (chars[i] >= 'a' && chars[i] <= 'z') {
                result.append(chars[i]);
            }
            if (chars[i] >= '0' && chars[i] <= '9') {
                result.append(chars[i]);
            }
        }
        return result.toString();
    }
}
